const { app, BrowserWindow, session } = require('electron')
const path = require('path')


const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false, // 允许在渲染进程中使用 Node.js API
      contextIsolation: true,
    },
    maximizable: true // 允许窗口最大化
  });

  win.maximize()
  win.loadURL('https://developer.open-douyin.com/login?service=https%3A%2F%2Fopen.douyin.com%2Fplatform')

  win.webContents.on('did-navigate', () => {
    const url = win.webContents.getURL();
    console.log("Navigated to:", url);

    // 检查是否登录成功，可以根据具体的登录成功页面来判断
    if (url == 'https://developer.open-douyin.com/') { // 修改此处的判断条件
      const cookies = session.defaultSession.cookies;

      cookies.get({ url })
        .then((cookies) => {
          console.log("Logged in URL: ", url, "Cookies: ", cookies);
          // 在这里可以处理cookies，比如保存到文件或发送到服务器
        }).catch((error) => {
          console.log(error);
        });
    }
  });

  // win.webContents.on('did-finish-load', () => {
  //   const url = win.webContents.getURL();
  //   const cookies = session.defaultSession.cookies;

  //   cookies.get({ url })
  //     .then((cookies) => {
  //       console.log("url: ", url, "cookies", cookies);
  //     }).catch((error) => {
  //       console.log(error);
  //     });
  // });

  // win.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow();

  // 注册协议
  const PROTOCOL = 'electronTest';
  app.setAsDefaultProtocolClient(PROTOCOL) // 注册协议

  app.on('open-url', (event, url) => {
    event.preventDefault();
    console.log('Received custom protocol call:', url);
    // 处理自定义协议逻辑
    mainWindow.webContents.send('protocol-request', url);
  });

});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

// 处理从其他实例传入的自定义协议
if (!app.requestSingleInstanceLock()) {
  app.quit();
} else {
  app.on('second-instance', (event, argv, workingDirectory) => {
    // Windows 下通过 protocol URL 启动的应用会在 argv 中包含这个 URL
    if (process.platform == 'win32') {
      let url = argv.find(arg => arg.startsWith('electronTest://'));
      if (url) {
        mainWindow.webContents.send('protocol-request', url);
      }
    }
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
    }
  });
}